<?php
namespace app\api\model;

use think\Model;

class Ticket extends Model{

    /**
     * 获取某一门票的套餐
     * @param $product_id 产品ID
     * @return array
     */
    public function getTicketSpecs($product_id)
    {
        //检查是否为门票产品
        $product = db('product p')->where(['use_type'=>3,'id'=>$product_id])->find();
        if(empty($product_id) || empty($product)) return ['code'=>4001,'门票产品不存在'];
        $package = db('product_package')->where('product_id',$product_id)->select();
        if(empty($package)) return ['code'=>4101,'msg'=>'门票产品未配置套餐'];
        $package_id = array_column($package,'id');
        $specs = db('product_specs')
            ->where(['package_id'=>['in',$package_id]])
            ->select();
        foreach ($package as $p_k=>$p_v){
            $package[$p_k]['child'] = [];
            foreach ($specs as $s_k=>$s_v){
                if($s_v['package_id']==$p_v['id']){
                    $package[$p_k]['child'][] = $s_v;
                    unset($specs[$s_k]);//匹配命中 删除节点
                }
            }
        }

        return $package;

    }

    /**
     * 获取门票的具体价格
     * @param $product_id 产品ID
     * @param $date 购买日期
     * @param $age 年龄
     * @return array
     */
    public function getTicketPriceByIDAndDate($product_id,$date,$age)
    {
        //检查是否为门票产品
        $product = db('product p')->where(['use_type'=>3,'p.id'=>$product_id])->find();
        if(empty($product_id) || empty($product)) return ['code'=>4001,'msg'=>'门票产品不存在'];
        $where['pd.product_id'] = $product_id;
        $where['pd.time'] = $date;
        if(!empty($age)){
            $where['ps.min_age'] = ['elt',$age];
            $where['ps.max_age'] = ['gt',$age];
        }
        //检查门票是否配置价格 关联用车和年龄区间
        $pricelist = db('product_dailyprice pd')
            ->join('product_specs ps','pd.specs_id=ps.id','left')
            ->field('pd.id,pd.time,pd.name,pd.price,pd.num,pd.minorder_num,pd.inc_order_num,
            pd.cost_currency,pd.exchange_num,ps.min_age,ps.max_age,ps.car_type')
            ->where($where)->select();
        if(!empty($pricelist)) return ['code'=>4002,'msg'=>'未查询到该区间的门票价格'];

        //匹配第一条数据
        $result = reset($pricelist) && current($pricelist);
        return $result;

    }


}